<template>
  <div class="edit-container">
    <el-card class="edit-card">
      <template #header>
        <h2 class="edit-title">编辑商品</h2>
      </template>
      
      <div v-if="loading" class="loading-wrapper">
        <el-skeleton :rows="10" animated />
      </div>
      
      <el-form
        v-else
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-width="100px"
        class="edit-form"
      >
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入商品名称" />
        </el-form-item>
        
        <el-form-item label="商品分类" prop="categoryId">
          <el-select v-model="editForm.categoryId" placeholder="请选择分类">
            <el-option
              v-for="category in categories"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="商品价格" prop="price">
          <el-input-number
            v-model="editForm.price"
            :min="0"
            :precision="2"
            placeholder="请输入价格"
          />
        </el-form-item>
        
        <!-- <el-form-item label="原价" prop="originalPrice">
          <el-input-number
            v-model="editForm.originalPrice"
            :min="0"
            :precision="2"
            placeholder="请输入原价"
          />
        </el-form-item> -->
        
        <el-form-item label="库存数量" prop="inventory">
          <el-input-number
            v-model="editForm.inventory"
            :min="1"
            :precision="0"
            placeholder="请输入库存"
          />
        </el-form-item>
        
        <el-form-item label="商品图片" prop="coverList">
          <el-upload 
            class="avatar-uploader" 
            name="image" 
            action="http://localhost:8080/user/upload"
            :on-success="handleAvatarSuccess" 
            :before-upload="beforeAvatarUpload" 
            :on-error="handleAvatarError"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
        
        <el-form-item label="商品描述" prop="description">
          <el-input
            v-model="editForm.description"
            type="textarea"
            :rows="6"
            placeholder="请详细描述商品信息..."
          />
        </el-form-item>
        
        <el-form-item label="可砍价">
          <el-switch v-model="editForm.isBargain" :active-value="1" :inactive-value="0" />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSave" :loading="saving">
            保存修改
          </el-button>
          <el-button @click="handleCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 图片预览对话框 -->
    <el-dialog v-model="dialogVisible" title="图片预览">
      <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { useProductStore } from '@/stores/product'
import request from '@/utils/request'
import type { UploadProps } from 'element-plus'

const route = useRoute()
const router = useRouter()
const productStore = useProductStore()

const editFormRef = ref()
const loading = ref(false)
const saving = ref(false)
const fileList = ref<any[]>([])
const dialogVisible = ref(false)
const dialogImageUrl = ref('')
const imageUrl = ref('')

const categories = ref<any[]>([])

const editForm = reactive({
  name: '',
  categoryId: undefined as number | undefined,
  price: 0,
  originalPrice: 0,
  inventory: 1,
  description: '',
  isBargain: 0,
  coverList: ''
})

const editRules = {
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 2, max: 50, message: '商品名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择商品分类', trigger: 'change' }
  ],
  price: [
    { required: true, message: '请输入商品价格', trigger: 'blur' }
  ],
  inventory: [
    { required: true, message: '请输入库存数量', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入商品描述', trigger: 'blur' },
    { min: 10, max: 1000, message: '商品描述长度在 10 到 1000 个字符', trigger: 'blur' }
  ]
}

const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  console.log('图片上传成功:', response)
  imageUrl.value = response.data
  editForm.coverList = imageUrl.value
  ElMessage.success('图片上传成功')
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('图片必须是 JPG 格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

const handleAvatarError: UploadProps['onError'] = (error, file) => {
  console.error('图片上传失败:', error)
  ElMessage.error('图片上传失败，请重试')
}

const loadCategories = async () => {
  try {
    const response = await request.get('/category/list', {
      params: {
        pageSize: 20,
      }
    })
    
    if (response && response.data) {
      const categoryData = Array.isArray(response.data) ? response.data : 
                          (response.data.data && Array.isArray(response.data.data)) ? response.data.data : []
      
      if (categoryData.length > 0) {
        categories.value = categoryData.filter((cat: any) => cat.isUse)
      } else {
        // 使用默认分类作为备选
        categories.value = [
          { id: 1, name: '电子产品' },
          { id: 2, name: '服装鞋帽' },
          { id: 3, name: '图书音像' },
          { id: 4, name: '家居用品' },
          { id: 5, name: '运动户外' }
        ]
      }
    }
  } catch (error: any) {
    console.error('获取分类失败:', error)
    // 使用默认分类作为备选
    categories.value = [
      { id: 1, name: '电子产品' },
      { id: 2, name: '服装鞋帽' },
      { id: 3, name: '图书音像' },
      { id: 4, name: '家居用品' },
      { id: 5, name: '运动户外' }
    ]
  }
}

const loadProductDetail = async () => {
  try {
    loading.value = true
    const productId = Number(route.params.id)
    const product = await productStore.getProductDetail(productId)
    
    if (product) {
      editForm.name = product.name || ''
      editForm.categoryId = product.categoryId
      editForm.price = product.price || 0
      editForm.originalPrice = (product as any).originalPrice || 0
      editForm.inventory = product.inventory || 1
      editForm.description = product.detail || '' // 后端使用detail字段
      editForm.isBargain = product.isBargain ? 1 : 0
      
      // 处理图片数据
      if (product.coverList) {
        editForm.coverList = product.coverList
        imageUrl.value = product.coverList
      }
    }
  } catch (error: any) {
    console.error('获取商品详情失败:', error)
    ElMessage.error('获取商品详情失败')
    router.push('/user/products')
  } finally {
    loading.value = false
  }
}

const handleSave = async () => {
  try {
    await editFormRef.value.validate()
    saving.value = true
    
    const productId = Number(route.params.id)
    await productStore.updateProduct({
      id: productId,
      name: editForm.name,
      categoryId: editForm.categoryId!,
      price: editForm.price,
      originalPrice: editForm.originalPrice,
      inventory: editForm.inventory,
      detail: editForm.description, // 后端使用detail字段
      isBargain: editForm.isBargain,
      coverList: editForm.coverList // 后端使用coverList字段
    })
    
    ElMessage.success('保存成功！')
    router.push('/user/products')
  } catch (error: any) {
    console.error('保存商品失败:', error)
    ElMessage.error('保存失败，请稍后重试')
  } finally {
    saving.value = false
  }
}

const handleCancel = () => {
  router.push('/user/products')
}

onMounted(() => {
  loadCategories()
  loadProductDetail()
})
</script>

<style scoped lang="scss">
.edit-container {
  padding: 30px;
  background: #f5f7fa;
  min-height: 100vh;
}

.edit-card {
  max-width: 800px;
  margin: 0 auto;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  
  :deep(.el-card__header) {
    background: linear-gradient(135deg, #ff6b35 0%, #f7931e 100%);
    color: white;
    border-radius: 12px 12px 0 0;
  }
}

.edit-title {
  text-align: center;
  margin: 0;
  color: white;
  font-size: 24px;
  font-weight: 600;
}

.loading-wrapper {
  padding: 40px;
}

.edit-form {
  margin-top: 20px;
  padding: 20px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #2c3e50;
}

:deep(.el-input__wrapper) {
  border-radius: 8px;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-textarea__inner) {
  border-radius: 8px;
}

:deep(.el-upload--picture-card) {
  border-radius: 8px;
}

.avatar-uploader {
  :deep(.el-upload) {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }

  :deep(.el-upload:hover) {
    border-color: var(--el-color-primary);
  }
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  line-height: 178px;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

:deep(.el-button) {
  border-radius: 8px;
  font-weight: 500;
  padding: 12px 24px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .edit-container {
    padding: 15px;
  }
  
  .edit-card {
    margin: 0;
  }
  
  .edit-title {
    font-size: 20px;
  }
  
  .edit-form {
    padding: 15px;
  }
}
</style> 